# Perko Ladislav

import sys
import System
import System.Threading
import clr
import time
import datetime
import xml.dom.minidom
import threading

sys.path.append(r'D:\ESL\PythonApplication1')
import napake
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("Microsoft.Scripting")
clr.AddReference('System.Drawing')
clr.AddReference("Microsoft.Office.Interop.Excel")

clr.AddReferenceToFileAndPath("IronPython.Wpf.dll")
import  wpf

from System import Action, AppDomain, UnhandledExceptionEventHandler, Type, Diagnostics, Net
from System.Collections import *
clr.AddReferenceByPartialName('MySql.Data')
from MySql.Data.MySqlClient import * 
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection
from System.Threading import *
from System.Threading.Tasks import *
from System.Windows.Threading import *
from System.Text.RegularExpressions import *
clr.AddReference ("SAP_dll")
from SAP_dll import *
from Microsoft.Office.Interop import Excel

from socket import *
from System.ComponentModel import BackgroundWorker
from System.Windows import Window
from napake import *
from System.Windows.Controls import *
from System.Drawing import *
from System.Windows.Forms import Timer
from System.Runtime.InteropServices import Marshal



class ObjectLocker(object):
      def __init__(self, obj):
              self.obj = obj
      def __enter__(self):
              Monitor.Enter(self.obj)
      def __exit__(self, *args):
              Monitor.Exit(self.obj)

conStrNtpe1 = 'server=ntpe1; userid=purkat; password=purkat; database=sledljivost;'
dbNtpe1 = MySqlConnection(conStrNtpe1) 

conStrPris = 'Data Source=vmie3;initial catalog=KAKOVOST;user id=uporabnik;password=uporabnik; Connect Timeout=30'
dbPris = SqlConnection(conStrPris)

def barva_obrazca(barva):    #{Red, Blue, Green};
    obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](obrazec.ChangeGrid), barva)

IT_VERZIJA = "0A0"
ASYS_VAR = "c:\\TedenskaKoda_FIELD.VARIABLE"
TICK = 0

#
# POVEZAVA Z NTPE1
#
def poizvedbaNTPE(stavek, izhod):
    l = ArrayList()
    i=0
    #print "NTPE: %s" %stavek
    with ObjectLocker(dbNtpe1):
        while dbNtpe1.State.ToString() != System.Data.ConnectionState.Open.ToString():  
            try:
              dbNtpe1.Open()
              cmd = dbNtpe1.CreateCommand() 
              cmd.CommandText = stavek
              r = cmd.ExecuteReader () 
              l = ArrayList()
              while r.Read (): 
                  vrednost = izhod
                  for x in range(r.FieldCount):
                      vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                  l.Add(vrednost)
              r.Close () 
              barva_obrazca('None')
            except Exception, e:
              debug.TraceDbg("Povezava na NTPE1 neuspesna!", e.message.ToString(), "Warning")
              System.Threading.Thread.Sleep(2000)
              if (i<2):
                barva_obrazca('Orange')
              else:
                barva_obrazca('Red')
              i=i+1
        dbNtpe1.Close () 
    return l

#
# POVEZAVA Z PRIS
#
def poizvedbaPRIS(stavek, izhod):
    l = ArrayList()
    i = 0
    #print "PRIS: %s" %stavek
    with ObjectLocker(dbPris):
        while dbPris.State.ToString() != System.Data.ConnectionState.Open.ToString():
          try:
              dbPris.Open()
              cmd = dbPris.CreateCommand() 
              cmd.CommandText = stavek
              r = cmd.ExecuteReader () 
              l = ArrayList()
              while r.Read (): 
                  vrednost = izhod
                  for x in range(r.FieldCount):
                      vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                  l.Add(vrednost)
              r.Close () 
              barva_obrazca('None')
          except Exception, e:
              debug.TraceDbg("Povezava na PRIS neuspesna!", "Stavek: %s\n%s" %(stavek, e.message.ToString()), "Warning")
              System.Threading.Thread.Sleep(1000)
              if (i<2):
                barva_obrazca('Orange')
              else:
                barva_obrazca('Red')
              i=i+1
        dbPris.Close () 
    return l


cb_dn = None
cb_procesna = None
tb_izd = None
tb_kol = None
tb_kol_asysA_PASS = None
tb_kol_asysB_PASS = None
timer = None
tb_procesna = None
debug.TraceDbg("Skripta verzija %s" %(IT_VERZIJA), None, "Info")

# refresh koliko plosc je na A in koliko na B strani
def refresh_kolicina_PASS(sender, args):
    global TICK
    TICK = TICK + 1
    try:
        barva_obrazca('Blue')
        Astran = poizvedbaNTPE("SELECT COUNT(`Procesna`) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%A' AND `Rezultat` LIKE 'PASS%%'" %(args.Argument[0]), "{COUNT(`Procesna`)}")
        Bstran = poizvedbaNTPE("SELECT COUNT(`Procesna`) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%B' AND `Rezultat` LIKE 'PASS%%'" %(args.Argument[0]), "{COUNT(`Procesna`)}")
        args.Result = [Astran[0], Bstran[0]]
    except Exception, e:
        debug.TraceDbg("PASS podatkov ni mogoce dobiti!", "%s" %(e.message.ToString()), "Warning")
        args.Result = ["n/a", "n/a"]
    TICK = TICK - 1

def refresh_kolicina_PASS_completed(sender, args):
    tb_kol_asysA_PASS.Content = args.Result[0]
    tb_kol_asysB_PASS.Content = args.Result[1]
    barva_obrazca('None')

def refresh_kolicina_FAIL(sender, args):
    global TICK
    TICK = TICK + 1
    try:
        barva_obrazca('Blue')
        Astran = poizvedbaNTPE("SELECT COUNT(`Procesna`) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%A' AND `Rezultat` LIKE 'FAIL%%'" %(args.Argument[0]), "{COUNT(`Procesna`)}")
        Bstran = poizvedbaNTPE("SELECT COUNT(`Procesna`) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%B' AND `Rezultat` LIKE 'FAIL%%'" %(args.Argument[0]), "{COUNT(`Procesna`)}")
        args.Result = [Astran[0], Bstran[0]]
    except Exception, e:
        debug.TraceDbg("FAIL podatkov ni mogoce dobiti!", "%s" %(e.message.ToString()), "Warning")
        args.Result = ["n/a", "n/a"]
    TICK = TICK - 1

def refresh_kolicina_FAIL_completed(sender, args):
    tb_kol_asysA_FAIL.Content = args.Result[0]
    tb_kol_asysB_FAIL.Content = args.Result[1]
    barva_obrazca('None')

def refresh_kolicina_REJECT(sender, args):
    global TICK
    TICK = TICK + 1
    try:
        barva_obrazca('Blue')
        Astran = poizvedbaNTPE("SELECT COUNT(`Procesna`) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%A' AND `Rezultat` LIKE 'REJECT%%'" %(args.Argument[0]), "{COUNT(`Procesna`)}")
        Bstran = poizvedbaNTPE("SELECT COUNT(`Procesna`) FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%B' AND `Rezultat` LIKE 'REJECT%%'" %(args.Argument[0]), "{COUNT(`Procesna`)}")
        args.Result = [Astran[0], Bstran[0]]
    except Exception, e:
        debug.TraceDbg("REJECT podatkov ni mogoce dobiti!", "%s" %(e.message.ToString()), "Warning")
        args.Result = ["n/a", "n/a"]
    TICK = TICK - 1

def refresh_kolicina_REJECT_completed(sender, args):
    tb_kol_asysA_REJECT.Content = args.Result[0]
    tb_kol_asysB_REJECT.Content = args.Result[1]
    barva_obrazca('None')

def dn_changed(sender, args):
    try:
        koda = poizvedbaPRIS("SELECT KODA FROM KAKOVOST.dbo.DELNALOGI WHERE DELNALOG IN ('%s');" %(cb_dn.SelectedItem.ToString()), "{KODA}")
        kolicina = poizvedbaPRIS("SELECT STMODULOV FROM KAKOVOST.dbo.DELNALOGI WHERE DELNALOG IN ('%s');" %(cb_dn.SelectedItem.ToString()), "{STMODULOV}")
        izdelek = poizvedbaPRIS("SELECT KODA FROM KAKOVOST.dbo.SEZKOD WHERE ID IN ('%s');" %(koda[0]), "{KODA}")
        tb_izd.Text = izdelek[0]
        tb_kol.Text = kolicina[0]
        onTick(None, None)
    except Exception, e:
        debug.TraceDbg("NAPAKA PRI POIZVEDBI V PRIS!", "%s" %(e.message.ToString()), "Warning")

def procesna_changed(sender, args):
    try:
        global tb_procesna
        global cb_procesna
        while obrazec.stackPanel6.Children.Count > 1:
            obrazec.stackPanel6.Children.RemoveAt(obrazec.stackPanel6.Children.Count - 1)
        if (tb_procesna.Text.Length != 10):
            return
        kodaA = poizvedbaNTPE("SELECT `Procesna` FROM `sledljivost`.`asysaba04` WHERE `Procesna` IN ('%sA') and  `DN` IN ('%s');" %(tb_procesna.Text.Substring(0, 9), cb_dn.SelectedItem.ToString()), "{Procesna}")
        kodaB = poizvedbaNTPE("SELECT `Procesna` FROM `sledljivost`.`asysaba04` WHERE `Procesna` IN ('%sB') and  `DN` IN ('%s');" %(tb_procesna.Text.Substring(0, 9), cb_dn.SelectedItem.ToString()), "{Procesna}")
        if (kodaA.Count == 1):
            chkb_procesnaA = System.Windows.Controls.CheckBox()
            chkb_procesnaA.Height = 23
            chkb_procesnaA.Content = kodaA[0]
            obrazec.stackPanel6.Children.Add(chkb_procesnaA)
            chkb_procesnaA.IsChecked = 1
        if (kodaB.Count == 1):
            chkb_procesnaB = System.Windows.Controls.CheckBox()
            chkb_procesnaB.Height = 23
            chkb_procesnaB.Content = kodaB[0]
            obrazec.stackPanel6.Children.Add(chkb_procesnaB)
            chkb_procesnaB.IsChecked = 1
        if (cb_procesna.IsChecked == 1):
            reject_click(None, None)

    except Exception, e:
        debug.TraceDbg("NAPAKA PRI POIZVEDBI V PRIS!", "%s" %(e.message.ToString()), "Warning")

def reject_click(sender, args):
    global tb_procesna
    for index in range(0, obrazec.stackPanel6.Children.Count):
        if (obrazec.stackPanel6.Children[index].GetType().ToString() == 'System.Windows.Controls.CheckBox'):
            if (obrazec.stackPanel6.Children[index].IsChecked == 1):
                poizvedbaNTPE("UPDATE `sledljivost`.`asysaba04` SET `Rezultat`='REJECT' WHERE `Procesna` IN ('%s') AND `DN` IN ('%s')" %(obrazec.stackPanel6.Children[index].Content, cb_dn.SelectedItem.ToString()), "")
    tb_procesna.Focus()
    onTick(None, None)

def info(sender, args):
    try:
        debug.richTextBox_debug.Document.Blocks.Clear()
        print "Izpis procesnih stevilk za %s:" %(sender.Name)
        stevilke = poizvedbaNTPE("SELECT  Procesna, Datum, DN, Ident, Prevzem, Prevzem2, ProcesnaSkupna, PanelPozicija, OperaterDS, OperaterPrijavljen, Program, Rezultat FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s')  AND `Rezultat` LIKE '%s%%' AND `Procesna` LIKE '%%%s'" %(cb_dn.SelectedItem.ToString(), sender.Name.Substring(1,sender.Name.Length - 1), sender.Name.Substring(0,1)), "{Procesna}\t{Datum}\t{DN}\t{Ident}\t{Prevzem}\t{Prevzem2}\t{ProcesnaSkupna}\t{PanelPozicija}\t{OperaterDS}\t{OperaterPrijavljen}\t{Program}\t{Rezultat}")
        for stevilka in stevilke:
            print('%s' %(stevilka)),
    except Exception, e:
        debug.TraceDbg("Napaka! Izberi Delovni nalog.", "%s" %(e.message.ToString()), "Warning")

def osvezi_click(sender, args):
    debug.TraceDbg("Osvezujem", None, "Info")
    try:
        request = Net.HttpWebRequest.Create('http://ntpe1/trace_incoming/CronAsysABA04.php')
        request.Timeout=2000;
        response = request.GetResponse()
        System.Diagnostics.Process.Start("c:\\TraceCopy.bat");
    except Exception, e:
        debug.TraceDbg("Upsala, osvezevanje je povrocilo tezavco.", "%s" %(e.message.ToString()), "Warning")

    onTick(None, None)

def storno_click(sender, args):
    try:
        dn = cb_dn.SelectedItem.ToString()
        if (System.Windows.Forms.MessageBox.Show("Ali zelis stornirati delovni nalog %s" %(dn), "Storno", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes):
            poizvedbaNTPE("UPDATE `asysaba04` SET `Rezultat`='REJECT_STORNO' WHERE  `DN`='%s' AND `Rezultat` LIKE 'PASS%%';" %(dn), "{Procesna}")
            print "Nalog storniran"
    except Exception, e:
        debug.TraceDbg("Napaka! Izberi Delovni nalog.", "%s" %(e.message.ToString()), "Warning")


def nasvet_click(sender, args):
    try:
        debug.richTextBox_debug.Document.Blocks.Clear()

        stevilkaA = poizvedbaNTPE("SELECT Procesna FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%A' AND `Rezultat` LIKE 'PASS%%'" %(cb_dn.SelectedItem.ToString()), "{Procesna}")
        stevilkaB = poizvedbaNTPE("SELECT Procesna FROM `sledljivost`.`asysaba04` WHERE `DN` IN ('%s') AND `Procesna` LIKE '%%B' AND `Rezultat` LIKE 'PASS%%'" %(cb_dn.SelectedItem.ToString()), "{Procesna}")
        stevilke = None
        print "Spisek PASS za delovni nalog %s" %(cb_dn.SelectedItem.ToString())
        if (stevilkaA.Count > 0):
            stevilke = stevilkaA
        else:
            stevilke = stevilkaB
        
        for stevilka in stevilke:
            a = ArrayList.IndexOf(stevilkaA, '%sA' %stevilka.ToString().Substring(0,9))
            b = ArrayList.IndexOf(stevilkaB, '%sB' %stevilka.ToString().Substring(0,9))
            P_a = None
            P_n = None
            if (a > 0):
                P_a = '%s' %stevilkaA[a]
            else:
                P_a = '       '

            if (b > 0):
                P_b = '%s' %stevilkaB[b]
            else:
                P_b = '       '
            print('%s\t%s' %(P_a, P_b))
    except Exception, e:
        debug.TraceDbg("Napaka! Izberi Delovni nalog.", "%s" %(e.message.ToString()), "Warning")


def getExcelKoda(tedkoda):
    try:
        ex = Excel.ApplicationClass()   
        ex.Visible = True
        ex.DisplayAlerts = False   

        workbook = ex.Workbooks.Open('c:\\jure.xls')
        ws = workbook.Worksheets[1]

        i=1
        while ws.Range["B"+str(i)].Text != '':  
            if (tedkoda == ws.Range["B"+str(i)].Text):
                neki = ws.Range["C"+str(i)].Text
                ex.Quit()
                return neki
            i = i + 1
        ex.Quit()
    except Exception, e:
        debug.TraceDbg("Napaka. Poizvedba iz excel tabele ne dela", "%s" %(e.message.ToString()), "Warning")

def getAsysKoda():
    global ASYS_VAR
    try:
        with open(ASYS_VAR) as f:
            file_str = f.read()

        return (file_str[78:81])
    except Exception, e:
        debug.TraceDbg("Napaka. Poizvedba iz asys ne dela", "%s" %(e.message.ToString()), "Warning")



def setAsysKoda(koda):
    global ASYS_VAR
    try:
        with open(ASYS_VAR) as f:
            file_str = f.read()

        old = file_str[78:81]
        file_str = file_str.replace(old, koda);

        with open(ASYS_VAR, "w") as f:
            f.write(file_str)
    except Exception, e:
        debug.TraceDbg("Napaka. Vpis na asys ne dela", "%s" %(e.message.ToString()), "Warning")

def asysupdate(sender, args):
    sender.Tag[0].Text = str(datetime.datetime.now().year)[2:4] + str(datetime.datetime.now().isocalendar()[1])
    sender.Tag[1].Text = getExcelKoda(sender.Tag[0].Text)
    setAsysKoda(sender.Tag[1].Text)
    sender.Tag[2].Text = getAsysKoda()

def morning_check(butn):
    asysupdate(butn, None)
    print("Naredil sem update tedenske kode")

# pobrisemo listek napake
def init():
    obrazec.tabControl1.Items.RemoveAt(2)
    obrazec.button_red.Visibility = System.Windows.Visibility.Hidden
    obrazec.button_green.Content = "REJECT"
    obrazec.button_green.Click += reject_click
    # delovni nalog
    obrazec.stackPanel2.Children.RemoveRange(0, obrazec.stackPanel2.Children.Count)
    obrazec.stackPanel1.Children.RemoveRange(0, obrazec.stackPanel1.Children.Count)
    obrazec.tabItem1.Header = "delovni nalog"
    # izloci TIV
    obrazec.stackPanel5.Children.RemoveRange(0, obrazec.stackPanel5.Children.Count)
    obrazec.stackPanel6.Children.RemoveRange(0, obrazec.stackPanel6.Children.Count)
    obrazec.tabItem2.Header = "izloci TIV"

    tab = TabItem();
    tab.Header = "Teden"
    obrazec.tabControl1.Items.Add(tab)
    l_tedkoda = Label()
    l_tedkoda.Content = "koda - YYWW"
    l_tedkoda_x = Label()
    l_tedkoda_x.Content = "koda - SAP"
    l_tedkoda_xx = Label()
    l_tedkoda_xx.Content = "koda - ASYS"
    b_update = Button()
    b_update.Click += asysupdate
    b_update.Content = "Osvezi!"

    teden_d = System.Windows.Controls.TextBox()
    teden_c = System.Windows.Controls.TextBox()
    teden_a = System.Windows.Controls.TextBox()
    #teden_d.Text = str(datetime.datetime.now().year)[2:4] + str(datetime.datetime.now().isocalendar()[1])
    #teden_c.Text = getExcelKoda(teden_d.Text)
    #teden_a.Text = getAsysKoda()
    b_update.Tag = [teden_d, teden_c, teden_a]
    asysupdate(b_update, None)

    LChild = StackPanel();
    LChild.Height = 167
    LChild.Width = 84
    LChild.HorizontalAlignment = System.Windows.HorizontalAlignment.Left
    LChild.VerticalAlignment = System.Windows.VerticalAlignment.Top
    DChild = StackPanel();
    DChild.Height = 167
    DChild.Margin = System.Windows.Thickness(90, 0, 0, 0);

    dgrid = System.Windows.Controls.Grid()
    LChild.Children.Add(l_tedkoda)
    LChild.Children.Add(l_tedkoda_x)
    LChild.Children.Add(l_tedkoda_xx)
    LChild.Children.Add(b_update)
    DChild.Children.Add(teden_d)
    DChild.Children.Add(teden_c)
    DChild.Children.Add(teden_a)

    dgrid.Children.Add(LChild)
    dgrid.Children.Add(DChild)

    tab.Content = dgrid

    ###########

    global tb_procesna
    cb_procesna = CheckBox()
    cb_procesna.Content = "Procesna"
    cb_procesna.Height = 23
    obrazec.stackPanel5.Children.Add(cb_procesna)
    tb_procesna = System.Windows.Controls.TextBox()
    tb_procesna.Height = 23
    obrazec.stackPanel6.Children.Add(tb_procesna)
    tb_procesna.TextChanged += procesna_changed
    

    ############



    global cb_dn
    l_dn = Label()
    l_dn.Content = "DELOVNI NAL"
    l_dn.Height = 23
    obrazec.stackPanel1.Children.Add(l_dn)
    cb_dn = System.Windows.Controls.ComboBox()
    cb_dn.Height = 23
    cb_dn.SelectionChanged += dn_changed
    obrazec.stackPanel2.Children.Add(cb_dn)
    
    
    global tb_izd
    l_izd = Label()
    l_izd.Content = "IZDELEK"
    l_izd.Height = 23
    obrazec.stackPanel1.Children.Add(l_izd)
    tb_izd = System.Windows.Controls.TextBox()
    tb_izd.IsReadOnly = 1
    tb_izd.Height = 23
    obrazec.stackPanel2.Children.Add(tb_izd)
    
    global tb_kol
    l_kol = Label()
    l_kol.Content = "KOLICINA"
    l_kol.Height = 23
    obrazec.stackPanel1.Children.Add(l_kol)
    tb_kol = System.Windows.Controls.TextBox()
    tb_kol.IsReadOnly = 1
    tb_kol.Height = 23
    obrazec.stackPanel2.Children.Add(tb_kol)

    refresh_btn = System.Windows.Controls.Button()
    refresh_btn.Content = "OSVEZI"
    refresh_btn.Height = 24
    obrazec.stackPanel2.Children.Add(refresh_btn)
    refresh_btn.Click += osvezi_click

    nasvet_btn = System.Windows.Controls.Button()
    nasvet_btn.Content = "NASVET"
    nasvet_btn.Height = 24
    obrazec.stackPanel2.Children.Add(nasvet_btn)
    nasvet_btn.Click += nasvet_click

    storno_btn = System.Windows.Controls.Button()
    storno_btn.Content = "STORNIRAJ DEL. NALOG"
    storno_btn.Height = 24
    obrazec.stackPanel2.Children.Add(storno_btn)
    storno_btn.Click += storno_click


    global tb_kol_asysA_PASS
    global tb_kol_asysB_PASS
    global tb_kol_asysA_FAIL
    global tb_kol_asysB_FAIL
    global tb_kol_asysA_REJECT
    global tb_kol_asysB_REJECT
    tb_PASS = Label()
    tb_FAIL = Label()
    tb_REJECT = Label()
    tb_kol_asysA = Label()
    tb_kol_asysB = Label()
    tb_kol_asysA_PASS = Label()
    tb_kol_asysB_PASS = Label()
    tb_kol_asysA_FAIL = Label()
    tb_kol_asysB_FAIL = Label()
    tb_kol_asysA_REJECT = Label()
    tb_kol_asysB_REJECT = Label()
    tb_kol_asysA_PASS.MouseUp += info
    tb_kol_asysB_PASS.MouseUp += info
    tb_kol_asysA_FAIL.MouseUp += info
    tb_kol_asysB_FAIL.MouseUp += info
    tb_kol_asysA_REJECT.MouseUp += info
    tb_kol_asysB_REJECT.MouseUp += info
    tb_kol_asysA_PASS.Name ="APASS"
    tb_kol_asysB_PASS.Name ="BPASS"
    tb_kol_asysA_FAIL.Name ="AFAIL"
    tb_kol_asysB_FAIL.Name ="BFAIL"
    tb_kol_asysA_REJECT.Name ="AREJECT"
    tb_kol_asysB_REJECT.Name ="BREJECT"
    tb_PASS.Content = "PASS"
    tb_FAIL.Content = "FAIL"
    tb_REJECT.Content = "REJECT"
    tb_PASS.Height = 30
    tb_FAIL.Height = 30
    tb_REJECT.Height = 30
    tb_kol_asysA.Content = "\"A\" STRAN:"
    tb_kol_asysB.Content = "\"B\" STRAN:"
    tb_kol_asysA_PASS.Content = "n/a"
    tb_kol_asysB_PASS.Content = "n/a"
    tb_kol_asysA_REJECT.Content = "n/a"
    tb_kol_asysB_REJECT.Content = "n/a"
    tb_kol_asysA_FAIL.Content = "n/a"
    tb_kol_asysB_FAIL.Content = "n/a"
    tb_kol_asysA.Height = 30
    tb_kol_asysB.Height = 30
    tb_kol_asysA_PASS.Height = 30
    tb_kol_asysB_PASS.Height = 30
    tb_kol_asysA_PASS.FontWeight = System.Windows.FontWeights.Bold
    tb_kol_asysB_PASS.FontWeight = System.Windows.FontWeights.Bold
    tb_kol_asysA_FAIL.Height = 30
    tb_kol_asysB_FAIL.Height = 30
    tb_kol_asysA_FAIL.FontWeight = System.Windows.FontWeights.Bold
    tb_kol_asysB_FAIL.FontWeight = System.Windows.FontWeights.Bold
    tb_kol_asysA_REJECT.Height = 30
    tb_kol_asysB_REJECT.Height = 30
    tb_kol_asysA_REJECT.FontWeight = System.Windows.FontWeights.Bold
    tb_kol_asysB_REJECT.FontWeight = System.Windows.FontWeights.Bold
    tb_kol_asysA.Margin = System.Windows.Thickness(15, 200, 15, 5)
    tb_kol_asysB.Margin = System.Windows.Thickness(15, 240, 15, 5)
    tb_kol_asysA_PASS.Margin = System.Windows.Thickness(100, 200, 25, 5)
    tb_kol_asysB_PASS.Margin = System.Windows.Thickness(100, 240, 25, 5)
    tb_kol_asysA_FAIL.Margin = System.Windows.Thickness(140, 200, 25, 5)
    tb_kol_asysB_FAIL.Margin = System.Windows.Thickness(140, 240, 25, 5)
    tb_kol_asysA_REJECT.Margin = System.Windows.Thickness(180, 200, 25, 5)
    tb_kol_asysB_REJECT.Margin = System.Windows.Thickness(180, 240, 25, 5)
    tb_PASS.Margin = System.Windows.Thickness(100, 160, 25, 5)
    tb_FAIL.Margin = System.Windows.Thickness(140, 160, 25, 5)
    tb_REJECT.Margin = System.Windows.Thickness(180, 160, 25, 5)
    obrazec.uiGridMain.Children.Add(tb_kol_asysA)
    obrazec.uiGridMain.Children.Add(tb_kol_asysB)
    obrazec.uiGridMain.Children.Add(tb_kol_asysA_PASS)
    obrazec.uiGridMain.Children.Add(tb_kol_asysB_PASS)
    obrazec.uiGridMain.Children.Add(tb_kol_asysA_FAIL)
    obrazec.uiGridMain.Children.Add(tb_kol_asysB_FAIL)
    obrazec.uiGridMain.Children.Add(tb_kol_asysA_REJECT)
    obrazec.uiGridMain.Children.Add(tb_kol_asysB_REJECT)
    obrazec.uiGridMain.Children.Add(tb_REJECT)
    obrazec.uiGridMain.Children.Add(tb_PASS)
    obrazec.uiGridMain.Children.Add(tb_FAIL)


    #### timer vsak dan zjutraj ob 5ih se neki nardi!

    x=datetime.datetime.today()
    y=x.replace(day=x.day, hour=x.hour, minute=x.minute+1, second=0, microsecond=0)
    delta_t=y-x
    secs=delta_t.seconds+1
    print(secs)
    t = threading.Timer(secs, morning_check, [b_update])
    t.start()


def onTick(sender, event):
    global TICK
    if (TICK > 0):
        return
    if (cb_dn.SelectedItem != None):
        worker1 = BackgroundWorker()
        worker2 = BackgroundWorker()
        worker3 = BackgroundWorker()
        worker1.DoWork += refresh_kolicina_PASS
        worker1.RunWorkerCompleted += refresh_kolicina_PASS_completed
        worker1.RunWorkerAsync([cb_dn.SelectedItem.ToString()])
        worker2.DoWork += refresh_kolicina_FAIL 
        worker2.RunWorkerCompleted += refresh_kolicina_FAIL_completed
        worker2.RunWorkerAsync([cb_dn.SelectedItem.ToString()])
        worker3.DoWork += refresh_kolicina_REJECT
        worker3.RunWorkerCompleted += refresh_kolicina_REJECT_completed
        worker3.RunWorkerAsync([cb_dn.SelectedItem.ToString()])


# nafila DELOVNI NAL
def nafilaj(nalogi):
    global cb_dn
    global timer
    cb_dn.ItemsSource = nalogi
    timer = Timer()
    timer.Interval = 30000
    timer.Tick += onTick
    timer.Start()
 
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action(init))
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](nafilaj), poizvedbaPRIS("SELECT DELNALOG FROM KAKOVOST.dbo.DELNALOGI;", "{DELNALOG}"))

